package com.cjb.cloudsecurity.exception;


import com.cjb.common.exception.ErrorCode;
import com.cjb.common.util.HttpContextUtils;
import com.cjb.common.util.JsonUtils;
import com.cjb.common.util.Result;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import java.io.IOException;

/**
 * @Author chenjinbin
 * @Package IntelliJ IDEA
 * @Class exception
 * @Date 2023-09-03 20:42
 */
public class SecurityAuthenticationEntryPoint implements AuthenticationEntryPoint {
    /**
     * 日志
     */
    private final static Logger log = LoggerFactory.getLogger(SecurityAuthenticationEntryPoint.class);
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException {
        response.setContentType("application/json; charset=utf-8");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Origin", HttpContextUtils.getOrigin());
        log.info("进入异常处理类");
        response.getWriter().print(JsonUtils.toJsonString(Result.error(ErrorCode.UNAUTHORIZED)));
    }
}